/**
 * API服务模块
 * 封装与后端API的通信逻辑
 */

// API服务类
class ApiService {
    constructor() {
        this.baseUrl = window.AppConfig.api.baseUrl;
        this.timeout = window.AppConfig.api.timeout;
        this.retryCount = window.AppConfig.api.retryCount;
        
        // 请求拦截器队列
        this.requestInterceptors = [];
        // 响应拦截器队列
        this.responseInterceptors = [];
        
        // 添加默认拦截器
        this.addDefaultInterceptors();
    }
    
    /**
     * 添加默认拦截器
     */
    addDefaultInterceptors() {
        // 请求拦截器：添加通用头部
        this.addRequestInterceptor((config) => {
            config.headers = config.headers || {};
            config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json';
            config.headers['X-Requested-With'] = 'XMLHttpRequest';
            
            // 添加时间戳防止缓存
            if (config.method === 'GET') {
                const separator = config.url.includes('?') ? '&' : '?';
                config.url += `${separator}_t=${Date.now()}`;
            }
            
            return config;
        });
        
        // 响应拦截器：统一错误处理
        this.addResponseInterceptor(
            (response) => {
                // 成功响应处理
                if (response.data && typeof response.data === 'object') {
                    // 检查业务状态码
                    if (response.data.code !== undefined && response.data.code !== 200) {
                        throw new Error(response.data.message || '请求失败');
                    }
                }
                return response;
            },
            (error) => {
                // 错误响应处理
                window.AppUtils.error('API请求错误:', error);
                
                let errorMessage = '网络请求失败';
                
                if (error.response) {
                    // 服务器响应错误
                    const status = error.response.status;
                    switch (status) {
                        case 400:
                            errorMessage = '请求参数错误';
                            break;
                        case 401:
                            errorMessage = '未授权访问';
                            break;
                        case 403:
                            errorMessage = '禁止访问';
                            break;
                        case 404:
                            errorMessage = '请求的资源不存在';
                            break;
                        case 500:
                            errorMessage = '服务器内部错误';
                            break;
                        default:
                            errorMessage = `请求失败 (${status})`;
                    }
                } else if (error.request) {
                    // 网络错误
                    errorMessage = '网络连接失败，请检查网络设置';
                } else {
                    // 其他错误
                    errorMessage = error.message || '未知错误';
                }
                
                throw new Error(errorMessage);
            }
        );
    }
    
    /**
     * 添加请求拦截器
     * @param {Function} interceptor - 拦截器函数
     */
    addRequestInterceptor(interceptor) {
        this.requestInterceptors.push(interceptor);
    }
    
    /**
     * 添加响应拦截器
     * @param {Function} onFulfilled - 成功处理函数
     * @param {Function} onRejected - 失败处理函数
     */
    addResponseInterceptor(onFulfilled, onRejected) {
        this.responseInterceptors.push({ onFulfilled, onRejected });
    }
    
    /**
     * 执行请求拦截器
     * @param {Object} config - 请求配置
     * @returns {Object} 处理后的配置
     */
    executeRequestInterceptors(config) {
        let processedConfig = config;
        for (const interceptor of this.requestInterceptors) {
            processedConfig = interceptor(processedConfig);
        }
        return processedConfig;
    }
    
    /**
     * 执行响应拦截器
     * @param {Object} response - 响应对象
     * @returns {Object} 处理后的响应
     */
    executeResponseInterceptors(response) {
        let processedResponse = response;
        for (const interceptor of this.responseInterceptors) {
            try {
                if (interceptor.onFulfilled) {
                    processedResponse = interceptor.onFulfilled(processedResponse);
                }
            } catch (error) {
                if (interceptor.onRejected) {
                    throw interceptor.onRejected(error);
                }
                throw error;
            }
        }
        return processedResponse;
    }
    
    /**
     * 基础请求方法
     * @param {Object} config - 请求配置
     * @returns {Promise} 请求Promise
     */
    async request(config) {
        // 处理请求配置
        const processedConfig = this.executeRequestInterceptors({
            method: 'GET',
            timeout: this.timeout,
            ...config,
            url: config.url.startsWith('http') ? config.url : `${this.baseUrl}${config.url}`
        });
        
        let lastError;
        
        // 重试逻辑
        for (let i = 0; i <= this.retryCount; i++) {
            try {
                const response = await this.executeRequest(processedConfig);
                return this.executeResponseInterceptors(response);
            } catch (error) {
                lastError = error;
                
                // 如果是最后一次重试或者是客户端错误（4xx），不再重试
                if (i === this.retryCount || (error.response && error.response.status >= 400 && error.response.status < 500)) {
                    break;
                }
                
                // 等待一段时间后重试
                await this.delay(Math.pow(2, i) * 1000); // 指数退避
            }
        }
        
        throw lastError;
    }
    
    /**
     * 执行实际的HTTP请求
     * @param {Object} config - 请求配置
     * @returns {Promise} 请求Promise
     */
    async executeRequest(config) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            
            // 设置超时
            xhr.timeout = config.timeout;
            
            // 设置响应类型
            xhr.responseType = 'json';
            
            // 事件处理
            xhr.onload = () => {
                const response = {
                    data: xhr.response,
                    status: xhr.status,
                    statusText: xhr.statusText,
                    headers: this.parseHeaders(xhr.getAllResponseHeaders()),
                    config: config,
                    request: xhr
                };
                
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(response);
                } else {
                    const error = new Error(`Request failed with status ${xhr.status}`);
                    error.response = response;
                    reject(error);
                }
            };
            
            xhr.onerror = () => {
                const error = new Error('Network Error');
                error.request = xhr;
                reject(error);
            };
            
            xhr.ontimeout = () => {
                const error = new Error('Request Timeout');
                error.request = xhr;
                reject(error);
            };
            
            // 打开请求
            xhr.open(config.method.toUpperCase(), config.url, true);
            
            // 设置请求头
            if (config.headers) {
                Object.keys(config.headers).forEach(key => {
                    xhr.setRequestHeader(key, config.headers[key]);
                });
            }
            
            // 发送请求
            const body = config.data ? (typeof config.data === 'string' ? config.data : JSON.stringify(config.data)) : null;
            xhr.send(body);
        });
    }
    
    /**
     * 解析响应头
     * @param {string} headerStr - 响应头字符串
     * @returns {Object} 解析后的响应头对象
     */
    parseHeaders(headerStr) {
        const headers = {};
        if (!headerStr) return headers;
        
        headerStr.split('\r\n').forEach(line => {
            const parts = line.split(': ');
            if (parts.length === 2) {
                headers[parts[0].toLowerCase()] = parts[1];
            }
        });
        
        return headers;
    }
    
    /**
     * 延迟函数
     * @param {number} ms - 延迟毫秒数
     * @returns {Promise} 延迟Promise
     */
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    /**
     * GET请求
     * @param {string} url - 请求URL
     * @param {Object} params - 查询参数
     * @param {Object} config - 额外配置
     * @returns {Promise} 请求Promise
     */
    get(url, params = {}, config = {}) {
        // 构建查询字符串
        const queryString = Object.keys(params)
            .filter(key => params[key] !== undefined && params[key] !== null)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join('&');
        
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        
        return this.request({
            method: 'GET',
            url: fullUrl,
            ...config
        });
    }
    
    /**
     * POST请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @param {Object} config - 额外配置
     * @returns {Promise} 请求Promise
     */
    post(url, data = {}, config = {}) {
        return this.request({
            method: 'POST',
            url: url,
            data: data,
            ...config
        });
    }
    
    /**
     * PUT请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @param {Object} config - 额外配置
     * @returns {Promise} 请求Promise
     */
    put(url, data = {}, config = {}) {
        return this.request({
            method: 'PUT',
            url: url,
            data: data,
            ...config
        });
    }
    
    /**
     * DELETE请求
     * @param {string} url - 请求URL
     * @param {Object} config - 额外配置
     * @returns {Promise} 请求Promise
     */
    delete(url, config = {}) {
        return this.request({
            method: 'DELETE',
            url: url,
            ...config
        });
    }
}

// 创建API服务实例
const apiService = new ApiService();

// 具体的API接口封装
window.API = {
    /**
     * 获取客户详情
     * @param {string} externalUserId - 外部联系人ID
     * @returns {Promise} 客户详情数据
     */
    async getCustomerDetail(externalUserId) {
        window.AppUtils.log('获取客户详情:', externalUserId);
        
        if (window.AppConfig.development.enableMockData) {
            // 模拟数据
            await apiService.delay(window.AppConfig.development.mockDelay);
            return {
                data: {
                    code: 200,
                    message: 'success',
                    data: {
                        externalUserId: externalUserId,
                        name: '张三',
                        avatar: 'https://via.placeholder.com/100x100?text=张三',
                        type: 1,
                        gender: 1,
                        unionId: 'union_' + externalUserId,
                        position: '产品经理',
                        corpName: '示例公司',
                        corpFullName: '示例科技有限公司',
                        externalProfile: {
                            externalCorpName: '客户公司',
                            externalAttr: []
                        },
                        followUsers: [
                            {
                                userId: 'user001',
                                remark: '重要客户',
                                description: '通过朋友介绍认识',
                                createTime: Date.now() - 86400000,
                                remarkCorpName: '备注公司名',
                                remarkMobiles: ['13800138000'],
                                addWay: {
                                    addWay: 1,
                                    wechatChannels: {
                                        nickname: '微信昵称',
                                        source: 1
                                    }
                                },
                                operUserId: 'user001',
                                tags: [
                                    {
                                        groupName: '客户类型',
                                        tagName: 'VIP客户',
                                        tagId: 'tag001',
                                        type: 1
                                    }
                                ]
                            }
                        ]
                    },
                    timestamp: new Date().toISOString()
                }
            };
        }
        
        const response = await apiService.get('/customer/detail', { externalUserId });
        return response;
    },
    
    /**
     * 批量获取客户详情
     * @param {Array<string>} externalUserIds - 外部联系人ID数组
     * @returns {Promise} 客户详情数据数组
     */
    async getCustomerDetailBatch(externalUserIds) {
        window.AppUtils.log('批量获取客户详情:', externalUserIds);
        
        if (window.AppConfig.development.enableMockData) {
            // 模拟数据
            await apiService.delay(window.AppConfig.development.mockDelay);
            return {
                data: {
                    code: 200,
                    message: 'success',
                    data: externalUserIds.map((id, index) => ({
                        externalUserId: id,
                        name: `客户${index + 1}`,
                        avatar: `https://via.placeholder.com/100x100?text=客户${index + 1}`,
                        type: 1,
                        gender: index % 2 + 1,
                        position: '职位' + (index + 1),
                        corpName: '公司' + (index + 1)
                    })),
                    timestamp: new Date().toISOString()
                }
            };
        }
        
        const response = await apiService.post('/customer/detail/batch', { externalUserIds });
        return response;
    },
    
    /**
     * 获取JSSDK配置
     * @param {string} url - 当前页面URL
     * @returns {Promise} JSSDK配置数据
     */
    async getJsSdkConfig(url) {
        window.AppUtils.log('获取JSSDK配置:', url);
        
        if (window.AppConfig.development.enableMockData) {
            // 模拟数据
            await apiService.delay(500);
            return {
                data: {
                    code: 200,
                    message: 'success',
                    data: {
                        beta: false,
                        debug: window.AppConfig.wechat.debug,
                        appId: window.AppConfig.wechat.corpId || 'mock_corp_id',
                        timestamp: Math.floor(Date.now() / 1000),
                        nonceStr: 'mock_nonce_' + Math.random().toString(36).substr(2, 15),
                        signature: 'mock_signature_' + Math.random().toString(36).substr(2, 40),
                        jsApiList: window.AppConfig.wechat.jsApiList
                    },
                    timestamp: new Date().toISOString()
                }
            };
        }
        
        const response = await apiService.get('/customer/jssdk-config', { url });
        return response;
    },
    
    /**
     * 获取用户信息
     * @param {string} code - 授权码
     * @returns {Promise} 用户信息数据
     */
    async getUserInfo(code) {
        window.AppUtils.log('获取用户信息:', code);
        
        if (window.AppConfig.development.enableMockData) {
            // 模拟数据
            await apiService.delay(500);
            return {
                data: {
                    code: 200,
                    message: 'success',
                    data: {
                        userId: 'mock_user_001',
                        name: '测试用户',
                        avatar: 'https://via.placeholder.com/100x100?text=测试',
                        mobile: '13800138000',
                        email: 'test@example.com',
                        department: ['技术部'],
                        position: '开发工程师'
                    },
                    timestamp: new Date().toISOString()
                }
            };
        }
        
        const response = await apiService.post('/customer/user-info', { code });
        return response;
    }
};

// 导出API服务（用于扩展）
window.ApiService = ApiService;

// 调试信息
if (window.AppConfig.development.enableDebugLog) {
    window.AppUtils.log('API服务已初始化');
    window.AppUtils.log('API基础URL:', apiService.baseUrl);
}